package com.example.h3x.androidmalware.View.Fragments;

import android.app.AlertDialog;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;

import com.example.h3x.androidmalware.R;
import com.ms.square.android.expandabletextview.ExpandableTextView;

import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;


public class MalwareFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_malware, container, false);
        //declaration a final variables of fragment components
        final CheckBox instagram = v.findViewById(R.id.instagram);
        final CheckBox twitter = v.findViewById(R.id.twitter);
        final CheckBox spotify = v.findViewById(R.id.spotify);

        final Button btnAttack = v.findViewById(R.id.button);
        final ExpandableTextView proc =  v.findViewById(R.id.item)
                .findViewById(R.id.expand_text_view);

        final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this.getActivity());

        // simple dialog message of warning
        alertDialogBuilder.setTitle("WARNING");
        View.OnClickListener attack = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (instagram.isChecked() && twitter.isChecked() && spotify.isChecked()){
                    alertDialogBuilder
                            .setMessage("The author does not bear any responsibility for the consequences, " +
                                    "the program only shows the possibilities of a simple deception of a man!")
                            .setCancelable(false)
                            .setPositiveButton("Continue",new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,int id) {
                                    //if user set the "yes", attack will starting
                                    //TODO
                                }
                            })
                            .setNegativeButton("No",new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    //closing dialog form
                                    dialog.cancel();
                                }
                            });


                    AlertDialog alertDialog = alertDialogBuilder.create();
                    alertDialog.show();
                }
            }
        };
        btnAttack.setOnClickListener(attack); //listener of pressing attack button



        String topPackageName = "";
        topPackageName = GetRunningProcesses(topPackageName);//calling method

        if (topPackageName.isEmpty()){
            proc.setText("Running processes:\n"+getString(R.string.ver_error));
//            inst.setEnabled(false);
            btnAttack.setEnabled(false);
        } else {
            proc.setText("Running processes:\n" + topPackageName);
        }

        return v;
    }



    private String GetRunningProcesses(String topPackageName){
        //getting running processes
        Context context = getContext();
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            UsageStatsManager mUsageStatsManager = (UsageStatsManager)context.getSystemService(Context.USAGE_STATS_SERVICE);
            long time = System.currentTimeMillis();
            // We get usage stats for the last 10 seconds
            List<UsageStats> stats = mUsageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000*10, time);
            // Sort the stats by the last time used
            if(stats != null) {
                SortedMap<Long,UsageStats> mySortedMap = new TreeMap<Long,UsageStats>();
                for (UsageStats usageStats : stats) {
                    mySortedMap.put(usageStats.getLastTimeUsed(),usageStats);
                }
                if(!mySortedMap.isEmpty()) {
                    topPackageName =  mySortedMap.get(mySortedMap.lastKey()).getPackageName();
                }
            }
            if (topPackageName.isEmpty()) topPackageName = "";
        }
        return topPackageName;

    }


}
